package farmer.gui;

import farmer.game.Data;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.geom.RoundRectangle2D;

import core.gui.Button;

public class BuildingButton extends Button{
	
	private BuildingGUI gui;
	private int type;
	private boolean hasEnoughRessource = false;
	private BuildingButtonPopup popup;

	public BuildingButton(String name, int type, BuildingGUI gui) {
		super(name);
		this.gui = gui;
		this.type = type;
		popup = new BuildingButtonPopup(type);
		isVisible = true;
		boundingRect = new RoundRectangle2D.Float(0, 0, 10, 10, 10, 10);
		setSize(50, 50);
	}
	
	private boolean isSelected = false;
	
	public void setSelected(boolean value){
		isSelected = value;
	}
	
	public void calculateRessource(){
		if(Data.hasRessourceToBuild(Data.wood, Data.rock, type)){
			hasEnoughRessource = true;
		}else{
			hasEnoughRessource = false;
			if(isSelected){
				gui.setSelection(-1);
			}
		}
	}
	
	@Override
	public void keyPressed(KeyEvent e){
		if(e.getKeyCode() == gui.getKeyCode(type)){
			isClicked();
		}
	}
	
	@Override
	public void isClicked() {
		calculateRessource();
		if(hasEnoughRessource){
			isSelected = !isSelected;
			if(isSelected){
				gui.setSelection(type);
			}else{
				gui.setSelection(-1);
			}
		}
	}
	
	@Override
	public void mousePressed(MouseEvent e){
		super.mousePressed(e);
		if(e.getButton() == MouseEvent.BUTTON3){
			isSelected = false;
			Data.building = -1;
		}
	}
	
	private Color color = new Color(0.7f, 0.7f, 0.7f, 0.8f);
	
	@Override
	public void render(Graphics2D g){
		if(!isVisible){
			return;
		}
		
		
		int px = input.getMouseX();
		int py = input.getMouseY();
		boolean contain = boundingRect.contains(px, py);
		if(isSelected){
			renderSelected(g);
		}else if(!contain){
			renderNormal(g);
		}else if(!isPressed){
			renderContains(g);
		}else if(isPressed){
			renderIsPressed(g);
		}
		drawButton(g);
		if(!hasEnoughRessource){
			int x=(int) (boundingRect.getX()-2);
			int y=(int) (boundingRect.getY()-2);
			int size = 50+4;
			g.setColor(color);
			g.fillRect(x, y, size, size);
		}
		if(this.isOver){
			popup.draw(g);
		}
	}
	
	//private Color colorSelected = new Color(237, 95, 7);
	private Color colorSelected2 = new Color(252, 158, 58);
	
	private void renderSelected(Graphics2D g){
		g.setColor(Color.WHITE);
		g.fill(boundingRect);
		g.setStroke(new BasicStroke(4));
		g.setColor(colorSelected2);
		g.draw(boundingRect);
	}

}
